<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;

class FsCompanyUserModel extends BaseModel
{
    protected $table = 'fs_company_users';

    protected $fillable = [
        'rmsUserId',
        'appId',
        'feishuId',
        'name',
        'phone',
        'source',
        'openId',
        'unionId',
        'avatar',
        'ext',
        'supplierDepartmentId',
        'supplierDepartmentName'
    ];

    const EXT_KF  = 0; // kf本部
    const EXT_OUT = 1;  // kf外部

    const SOURCE_DEFAULT = 0;
    const SOURCE_QUALITY_CONTROL = 1;  // 来源与品控

    public static function add(string $appId, string $feishuId, array $data)
    {
        return self::query()->updateOrCreate(['appId' => $appId, 'feishuId' => $feishuId], $data);
    }

    public static function saveRmsUserId(int $id, ?int $rmsUserId): int
    {
        if ($rmsUserId === null) {
            return 0;
        }

        return self::query()->where('id', $id)->update(['rmsUserId' => $rmsUserId]);
    }

    /**
     * 判断是否为三方供应商
     * @return bool
     */
    public static function checkExt(int $userId, string $feishuId): bool
    {
        return (bool)FsCompanyUserModel::query()
                                       ->where('rmsUserId', $userId)
                                       ->where('feishuId', $feishuId)
                                       ->where('ext', self::EXT_OUT)
                                       ->count();
    }

    /**
     * 获取feishuId - 只能拿外部的
     * @param int $rmsUserId
     * @param string $departmentId
     * @return string
     */
    public static function getFeishuId(int $rmsUserId, string $departmentId = ''): string
    {
        return (string)FsCompanyUserMappingModel::query()
                                                ->where('rmsUserId', $rmsUserId)
                                                ->when($departmentId, function ($query) use ($departmentId) {
                                                    $fsCompanyId = FsCompanyModel::query()
                                                                                 ->where('departmentId', $departmentId)
                                                                                 ->value('id') ?? 0;

                                                    $query->where('fsCompanyId', $fsCompanyId);
                                                })
                                                ->value('feishuId');
    }

    public static function getDepartmentIdByRmsUserId(int $rmsUserId)
    {
        $fsCompanyIds = FsCompanyUserMappingModel::query()->where('rmsUserId', $rmsUserId)->pluck('fsCompanyId');

        return FsCompanyModel::query()->whereIn('id', $fsCompanyIds)->groupBy('departmentId')->pluck('departmentId');
    }

    public static function filterKfUsers(array $rmsUserIds)
    {
        // 过滤出自己人
        $testCompanyId = FsCompanyModel::query()
                                       ->where('departmentId', FsCompanyModel::TEST_DEPARTMENT_ID)
                                       ->value('id');

        return FsCompanyUserMappingModel::query()
                                        ->whereIn('rmsUserId', $rmsUserIds)
                                        ->where('fsCompanyId', '!=', $testCompanyId)
                                        ->groupBy('rmsUserId')
                                        ->select('rmsUserId', 'feishuId')
                                        ->get()
                                        ->keyBy('rmsUserId');
    }

    /**
     * 获得用户与公司的关联
     * @return HasMany
     */
    public function fsCompanyUserMappingRel(): HasMany
    {
        return $this->hasMany(FsCompanyUserMappingModel::class, 'rmsUserId', 'rmsUserId');
    }
}
